/**
 * 视频播放
 */
import { defineComponent, Teleport, CSSProperties, ref, PropType, watchEffect, unref } from 'vue'

export default defineComponent({
  name: 'VideoPlayer',
  props: {
    modelValue: {
      type: Boolean as PropType<boolean>,
      default: false
    },
    url: {
      type: String as PropType<string>,
      default: ''
    },
    width: {
      type: String as PropType<string>,
      default: '50vw'
    },
    height: {
      type: String as PropType<string>,
      default: '50vh'
    }
  },
  emits: ['update:modelValue'],
  setup(props, ctx) {
    const show = ref(false)
    const src = ref(props.url)
    let refV: Nullable<HTMLVideoElement> = null
    watchEffect(() => {
      show.value = props.modelValue
      if (!show.value) {
        refV?.pause()
      } else if (refV?.played.length) {
        refV?.play()
      }
    })
    watchEffect(() => {
      src.value = props.url
    })
    return () => {
      const maskStyles: CSSProperties = {
        position: 'fixed',
        top: 0,
        left: 0,
        right: 0,
        bottom: 0,
        zIndex: 9999,
        backgroundColor: 'rgba(0,0,0,.5)'
      }
      const videoStyles: CSSProperties = {
        width: props.width,
        height: props.height,
        objectFit: 'contain',
        position: 'absolute',
        top: '50%',
        left: '50%',
        transform: 'translate(-50%, -50%)',
        outline: 'none',
        background: '#000'
      }
      const closeStyles: CSSProperties = {
        fontSize: '24px',
        color: '#fff',
        cursor: 'pointer',
        position: 'absolute',
        right: '10vw',
        top: '10vh'
      }
      const events = {
        onClick: (e: Event) => {
          e.stopPropagation()
          show.value = !show.value
          ctx.emit('update:modelValue', show.value)
        }
      }
      function preventDefault(e: Event) {
        e.stopPropagation()
      }
      function refVideo(node: HTMLVideoElement) {
        refV = node
      }
      return (
        <Teleport to='#app-mask' disabled={!unref(show)}>
          <div class="video-wrap" { ...events } v-show={unref(show)} style={ maskStyles }>
            <video ref={refVideo} style={videoStyles} onClick={preventDefault} controls autoplay src={unref(src)}></video>
            <div style={closeStyles} { ...events }>
              <i class="el-icon-close"></i>
            </div>
          </div>
        </Teleport>
      )
    }
  }
})
